import * as ts from 'typescript';

import { format2dts } from '../format';
import { outputFileSync } from '../utils';
import logger from '../utils/logger';

const path = require('path');
const fs = require('fs');

const computed = (file: string) => (file.endsWith('.js') ? file : `${file}.js`);

const transpileOptions = { compilerOptions: { module: ts.ModuleKind.CommonJS } };

export default function createTransfer (transpile: ts.TranspileOptions = transpileOptions) {
	return function transfer (input: string, output: string) {
		if (input === '') return;
		const compeleted = computed(output);
		const __local = process.cwd();
		const file = path.resolve(__local, input);

		let content = input;
		if (file.endsWith('.ts') && fs.existsSync(file)) {
			content = fs.readFileSync(file, 'utf-8');
		}

		try {
			const target = path.resolve(__local, compeleted);
			const r = ts.transpileModule(content, transpile);
			outputFileSync(target, format2dts(r.outputText));
			logger.success(compeleted);
			logger.success('√ API 生成完毕，已输出到上述文件');
		} catch (error) {
			logger.error(error.message);
		}
	};
}
